//check cookie
if($.cookie('kuki') != null) {
	window.location.replace('main.html');
} else {
}

$().ready(function() {
	
	//login button function
	$("#login_button").button().click(function() {
		var login = $(".topbar_login_container input")[0].value;
		var password = $(".topbar_login_container input")[1].value;
		if (!login || !password) {
			alert ("Please enter username and password");
		} else {
			$.post('/'+context+'/resources/users/login/' + login,
					JSON.stringify({password: password}))
					.success(function(data){
						$.cookie(data["cookie-name"], data.cookie);
						window.location = "main.html";})
					.error(function(data){	
						alert (data.responseText);
			});				
		}
	});
	
	//join button
	$("#join_button").button();
	
	
	// validate signup form on keyup and submit
	$("#join_form").validate({
		rules: {
			firstname: "required",
			lastname: "required",
			username: {
				required: true,
				minlength: 3
			},
			password: {
				required: true,
				minlength: 4
			},
			confirm_password: {
				required: true,
				minlength: 4,
				equalTo: "#password"
			}
		},
		messages: {
			firstname: "Please enter your firstname",
			lastname: "Please enter your lastname",
			username: {
				required: "Please enter a username",
				minlength: "Your username must consist of at least 3 characters"
			},
			password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 4 characters long"
			},
			confirm_password: {
				required: "Please provide a password",
				minlength: "Your password must be at least 4 characters long",
				equalTo: "Please enter the same password as above"
			}
		}
	});

	// propose username
	$("#username").focus(function() {
		var firstname = $("#firstname").val();
		if(firstname && !this.value) {
			this.value = firstname;
		}
	});
});

//registration function
function join() {
	var first = $(".loggedout_join_container input")[0].value;
	var last = $(".loggedout_join_container input")[1].value;
	var name = first + " " + last;
	var username = $(".loggedout_join_container input")[2].value;
	var password = $(".loggedout_join_container input")[3].value;
	$.post(
			'/'+context+'/resources/users/' + username,
			JSON.stringify({name: name, password: password})
		).success(function(data){
			$.post(
					'/'+context+'/resources/users/login/' + username,
					JSON.stringify({password: password})
				).success(function(data){
					$.cookie(data["cookie-name"], data.cookie);
					window.location = "main.html"; 
				}).error(function(data){
					alert("Managed to register, but unable to login! "+data.responseText);
			});
		}).error(function(data){
			alert("Unable to register! "+data.responseText);
		});
	
}